package bsts.view.bill;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import bsts.model.*;

import bsts.application.BSTSApplication;
import bsts.controller.BillController;
import bsts.controller.CustomerController;
import bsts.exception.BadGenerateBillException;
//Author - Than Htet Aung - A0079950R : 26-March-2011
public class ManageBillWindow extends JFrame{
	JLabel accountLbl;
	JLabel customerLbl;
	JLabel billLbl;
	JList customerList;
	JComboBox accountCombo;
	JList billList;
	JButton viewBillBtn;
	JButton generateCurrentMonthBillBtn;
	JPanel customerPnl;
	JPanel accountPnl;
	JPanel billPnl;
	JLabel messasgeLbl;
	ArrayList<Customer> customers;
	ArrayList<Bill> customer_account_Bill;
	public static final String BILL_LIST_DATE_FORMAT = "MMM-yyyy";
	private SimpleDateFormat billListDateFormat;
	private BillController billController;
	private BillApplication billManager;
	private BSTSApplication manager;
	JFrame self;
	/*
	 * 
	 *      this.manager = manager;
        setLayout (new BorderLayout());
        memberList = new java.awt.List (5);
        memberList.setMultipleMode (false);
        add ("North", new JLabel ("Members"));
        add ("Center", memberList);
        add ("East", createButtonPanel());
	 */
	
	public ManageBillWindow(BillApplication billApp){
		presetAttributes();
		this.billManager = billApp;
		buildUI();			
		setAction();
        this.setTitle("Manage bill");
	}
	
	public ManageBillWindow(BSTSApplication manager) {
		this.manager = manager;
		presetAttributes();
		//this.billManager = billApp;
		buildUI();			
		setAction();
		this.setTitle("Manage bill");
	}

	private void setAction() {
		self = this;
		this.addWindowListener( new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				System.out.println("Closing the window");	
				//billManager.shutDown();
				manager.getViewManager().goBackMain(self);
			}
		});
		ListSelectionListener listSelectionListener = new ListSelectionListener() {
		      public void valueChanged(ListSelectionEvent listSelectionEvent) {	
		    	  refreshAccounts();		    	 
		      }
		    };
		customerList.addListSelectionListener(listSelectionListener);
		
		accountCombo.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				refreshBills();
			}			
		});
	}

	private void buildUI() {
		customerPnl = new JPanel(new BorderLayout());		
		accountPnl = new JPanel(new BorderLayout());
		billPnl = new JPanel(new BorderLayout());
		customerLbl = new JLabel("Customers");		
		accountLbl = new JLabel("Accounts");
		billLbl = new JLabel("Bill");
		this.messasgeLbl = new JLabel("");
		customerList = new JList();
		customerList.setSize(100,100);
		customerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		billList = new JList();
		billList.setSize(100,200);
		accountCombo = new JComboBox();					
		customerPnl.add("North",customerLbl);
		customerPnl.add("Center",customerList);		
		accountPnl.add("North",accountLbl);
		accountPnl.add("South",accountCombo);
		customerPnl.add("South",accountPnl);
		billPnl.add("North",billLbl);
		billPnl.add("Center",billList);
		billPnl.add("East",createButtonPanel());
		billPnl.add("South",messasgeLbl);
		JPanel p = new JPanel ();
        //p.setLayout (new GridLayout(0, 1));
		p.setLayout (new GridLayout(0, 1));
        p.add (customerPnl);       
        p.add (billPnl);	      
        this.add ("Center", p);   
        if(!manager.isAdminRole()){
        	generateCurrentMonthBillBtn.setVisible(false);
        }
	}

	private void presetAttributes() {
		billListDateFormat = new SimpleDateFormat(BILL_LIST_DATE_FORMAT);
		billController = new BillController();
		customer_account_Bill = new ArrayList<Bill>();
		customers = new ArrayList<Customer>();
	}
	
	private JPanel createButtonPanel () {
        JPanel p = new JPanel (new GridLayout (0, 1));
        viewBillBtn = new JButton ("View Bill");
        viewBillBtn.addActionListener (new ActionListener () {
            public void actionPerformed (ActionEvent e) {
            	viewBill();
            }
        });
        p.add (viewBillBtn);

        generateCurrentMonthBillBtn = new JButton ("Generate Bill");
        generateCurrentMonthBillBtn.addActionListener (new ActionListener () {
            public void actionPerformed (ActionEvent e) {
            	System.out.println("Click Generate bill");
               generateBill();
            }
        });
        p.add (generateCurrentMonthBillBtn);
        JPanel bp = new JPanel ();
        bp.setLayout (new BorderLayout());
        bp.add ("North", p);
        return bp;
    }
	
	public void refresh(){
		System.out.println("in the refresh");
		CustomerController customerController = new CustomerController();
		this.customers= customerController.getCustomers();		
		String AccountString[] = new String[customers.size()];		
		for(int i=0;i<customers.size();i++)
		{
			// alert
			ArrayList<Account> accs = customers.get(i).getAccounts();
			if(accs.size() > 0){
				AccountString[i] = customers.get(i).toString();
			}			
		}
		customerList.removeAll(); 
		this.customerList.setListData(AccountString);	
		if(customers.size() > 0){
			customerList.setSelectedIndex(0);			
		}
	}
	public void refreshAccounts(){
		int index = customerList.getSelectedIndex();
		System.out.println("In Refresh bill , account - customer list index = "+index);
		if(index > -1){			
			ArrayList<Account> accs = this.customers.get(index).getAccounts();
			System.out.println("Number of accunt on the customer = "+accs.size());
			this.accountCombo.removeAll();
			if(accs.size() > 0){
				String AccListStr[] = new String[accs.size()];
				for(int i=0;i<accs.size();i++){
					AccListStr[i] = accs.get(i).getAccountNo();
					this.accountCombo.addItem(accs.get(i).getAccountNo());
				}
				this.accountCombo.setSelectedIndex(0);
			}			
		}
	}
	
	public void refreshBills(){
		int index = customerList.getSelectedIndex();
		int account_index = this.accountCombo.getSelectedIndex();
		System.out.println("In Refresh bill , account - customer list index = "+index);
		if(index > -1 && account_index > -1){			
			ArrayList<Account> accs = this.customers.get(index).getAccounts();
			System.out.println("Number of accunt on the customer = "+accs.size());			
			Account selectedAccount = accs.get(account_index);
			this.customer_account_Bill = this.billController.getBills(selectedAccount);
			System.out.println("Number of bill for this account = "+customer_account_Bill.size());
			String billListStr[] = new String[customer_account_Bill.size()];
			for(int i=0;i<customer_account_Bill.size();i++){
				billListStr[i] = billListDateFormat.format(customer_account_Bill.get(i).getBillDate());
			}
			this.billList.removeAll();
			this.billList.setListData(billListStr);
		}
	}
	
	public void viewBill(){
		int bill_index = this.billList.getSelectedIndex();
		int customer_index = customerList.getSelectedIndex();
		int account_index = accountCombo.getSelectedIndex();
		if(bill_index > -1 && account_index > -1 && customer_index > -1){
			ArrayList<Account> accounts = this.customers.get(customer_index).getAccounts();
			Account selectedAccount = accounts.get(account_index);
			Bill currentBill = this.customer_account_Bill.get(bill_index);			
			String billStr = this.billController.getMonthlyBill(selectedAccount.getAccountNo(), currentBill);
			System.out.println(billStr);
			System.out.println("Before displaying the bill");
			//JOptionPane.showMessageDialog(this,billStr);
			ViewBill vBillDialog = new ViewBill(this,billStr);
			System.out.println("After displaying the bill");
		}
	}
	
	public void generateBill(){
		int index = customerList.getSelectedIndex();
		System.out.println(" Account Customer list index = " + index);
		if(index > -1){
			//Need to change with current login user
			//// alert
			User regUser = manager.getLoginUser();
			System.out.println("After creating user");
			try{
				System.out.print( this.customers.get(index).getCustomerStringForBill());
				ArrayList<Account> accs = customers.get(index).getAccounts();
				if(accs.size() > 0){
					int accountIndex = accountCombo.getSelectedIndex();
					Account selectedAccount = accs.get(accountIndex);
					System.out.println("Account no = "+selectedAccount.getAccountNo());
					System.out.println("Before creating monthly bill");
					this.billController.createMonthlyBill(selectedAccount, regUser);
					System.out.println("After creating monthly bill");
					refreshBills();
					messasgeLbl.setText("Bill is successfully generated");
				}				
			}catch(BadGenerateBillException bbe){
				this.messasgeLbl.setText(bbe.getMessage());
				System.out.println(bbe.getMessage());
			}catch(Exception eee){
				this.messasgeLbl.setText("Contact system admin now! Error \n"+eee.getMessage());
				System.out.println(eee.getMessage());
			}
		}
	}
}
